package com.neurotech.pcc.ui

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.MotionEvent
import android.widget.EditText
import androidx.navigation.Navigation
import com.neurotech.pcc.R
import com.neurotech.pcc.other.Utils
import com.neurotech.pcc.other.toast

/**
 * MainActivity
 * @author shenhua
 */
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    override fun dispatchTouchEvent(event: MotionEvent): Boolean {
        if (event.action == MotionEvent.ACTION_DOWN) {
            val view = currentFocus
            if (view is EditText) {
                val leftTop = IntArray(2)
                view.getLocationInWindow(leftTop)
                val left = leftTop[0]
                val top = leftTop[1]
                val bottom = top + view.getHeight()
                val right = left + view.getWidth()
                if (event.x <= left || event.x >= right || event.y <= top || event.y >= bottom) {
                    Utils.hideKeyBoard(this)
                }
            }
        }
        return super.dispatchTouchEvent(event)
    }

    private var firstTime: Long = 0

    override fun onBackPressed() = try {
        val id = Navigation.findNavController(this, R.id.container).currentDestination?.id
        if (id == R.id.mainFragment) {
            if (firstTime + 2000 > System.currentTimeMillis()) {
                finish()
            } else {
                toast(getString(R.string.exit_again))
            }
            firstTime = System.currentTimeMillis()
        } else {
            super.onBackPressed()
        }
    } catch (e: Exception) {
        finish()
    }
}
